package com.study.common.util;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtils {

    /**
     * @description 组装参数
     * @author hw
     * @date 2022/1/24 14:51:54
     * @param requestUrl:请求地址
     * @param cookies:登录cookies
     * @param filepath:附件从属id
     * @param groupname:登录编码
     * @param webInput: 文件流
     * @param fileName: 文件名
     * @return com.alibaba.fastjson.JSONObject
     */
    public static JSONObject uploadFile(String requestUrl, List<String> cookies, String filepath, String groupname,
                                        InputStream webInput, String fileName) {
        HashMap<String, String> formTexts = new HashMap<>();
        formTexts.put("filepath", filepath);
        formTexts.put("groupname", groupname);
        formTexts.put("url", "true");
        formTexts.put("isreplace", "true");
        String result = FileUtils.uploadFilesPost(requestUrl, cookies, formTexts, webInput, fileName);
        return JSONObject.parseObject(result);
    }

    /**
     * @description 上传附件
     * @author hw
     * @date 2022/1/24 14:52:07
     * @param requestUrl:请求地址
     * @param cookies:登录cookies
     * @param webInput: 文件流
     * @param fileName: 文件名
     * @return java.lang.String 
     */
    public static String uploadFilesPost(String requestUrl, List<String> cookies, Map<String, String> formTexts,
                                         InputStream webInput, String fileName) {
        OutputStream out = null;
        BufferedReader reader = null;
        String result = "";
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            URL realUrl = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (cookies != null && cookies.size() > 0) {
                StringBuffer sb = new StringBuffer();
                for (String h : cookies) {
                    sb.append(h).append(";");
                }
                connection.addRequestProperty("Cookie", sb.toString());
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

            String boundary = "-----------------------------" + String.valueOf(System.currentTimeMillis());
            connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
            out = new DataOutputStream(connection.getOutputStream());
            if (formTexts != null && formTexts.size() > 0) {
                StringBuilder sbFormData = new StringBuilder();
                for (Map.Entry<String, String> entry : formTexts.entrySet()) {
                    sbFormData.append("--" + boundary + "\r\n");
                    sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                    sbFormData.append(entry.getValue() + "\r\n");
                }
                out.write(sbFormData.toString().getBytes("UTF-8"));
            }
            out.write(("--" + boundary + "\r\n").getBytes("UTF-8"));
            out.write(("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + fileName + "\"\r\n")
                    .getBytes("UTF-8"));
            out.write(("Content-Type: application/x-msdownload\r\n\r\n").getBytes("UTF-8"));
            DataInputStream in = new DataInputStream(webInput);
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            out.write(("\r\n").getBytes("UTF-8"));
            out.write(("--" + boundary + "--").getBytes("UTF-8"));
            out.flush();
            out.close();
            out = null;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
